package cn.jhc.listener;

import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.apache.commons.dbutils.QueryRunner;
import org.h2.jdbcx.JdbcDataSource;

import cn.jhc.Global;
import cn.jhc.bean.Article;
import cn.jhc.bean.User;
import cn.jhc.db.ArticleDao;
import cn.jhc.db.UserDao;


@WebListener
public class MyContextListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		String path = sce.getServletContext().getRealPath("/h2demo");
		System.out.println(path);
		JdbcDataSource ds = new JdbcDataSource();
		ds.setURL("jdbc:h2:" + path);
		String sql = "create table if not exists user("
				+ "id int auto_increment primary key,"
				+ "username varchar(128) unique not null,"
				+ "password varchar(128) not null,"
				+ "filename varchar(128) not null,"
				+ "sex char(1) not null,"
				+ "interests varchar(128))";	
		String sql1 = "create table if not exists article("
				+ "id int auto_increment primary key,"
				+ "title varchar(256) not null,"
				+ "content text,"
				+ "publishDate datetime not null,"
				+ "userId int references user(id))";
		QueryRunner runner = new QueryRunner(ds);
		sce.getServletContext().setAttribute(Global.KEY_QUERY_RUNNER, runner);
		try {
			runner.execute(sql);
			runner.execute(sql1);
			inserData(runner);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void inserData(QueryRunner runner) throws SQLException {
		for( int i = 0; i < 20; i++) {
			User user = new User("user" +i , "pass" + i, "file" + i, "M", "");
			if (UserDao.exists(runner, "user" + i)) {
				break;
				
			}
			UserDao.register(runner, user);
			User u = UserDao.login(runner, "user" + i, "pass" + i);
			for( int j = 0; j < 100; j ++) {
				Article article = new Article();
				article.setTitle("title" + i);
				article.setContent("content" + i);
				article.setPublishDate(new Date());
				article.setUserId(u.getId());
				ArticleDao.add(runner, article);
			}
		}
	}

}
